<template>
  <div class="w-full h-full flex">

<!--    <div class="w-1/2 h-full rounded-xl bg-white mr-2.5 p-3">-->
<!--      <material-storage-list/>-->
<!--    </div>-->
    <div class="w-full h-full p-3 rounded-xl border-slate-200 bg-white">
      <div class="flex items-center mb-2">
        <div class="flex items-center bg-indigo-50/60 rounded-lg py-0.5 px-2">
          <i class="iconfont icon-shishikucunshiyitu text-indigo-500 text-base"/>
          <span class="title font-semibold text-indigo-600 ml-1.5">条码入库信息</span>
        </div>
        <div class="flex-1 h-[1px] bg-gradient-to-r from-indigo-200 via-indigo-100/50 to-transparent ml-3"></div>

        <el-form :inline="true" :model="from"  class="align-center search-form">
          <el-form-item class="label" label="时间">
            <el-date-picker
              style="width: 220px"
              v-model="from.time"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              class="custom-date-picker"
            />
          </el-form-item>

          <el-form-item class="label" label="状态">
            <el-select v-model="from.status" clearable  placeholder="请选择">
              <el-option
                v-for="item in statusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-button icon="Search" class="buttons" size="small" type="primary" @click="getSerch">查询</el-button>
        </el-form>
      </div>
      <div class="w-full flex items-center mt-4" style="height: 88%">
        <div class="w-9/12 h-full"  style="background-color: rgba(209,208,208,0.2); border-radius: 16px;">
          <v-chart ref="currentRef" v-if="list.length"/>
          <el-empty v-else description="暂无数据" />
        </div>
        <div class="item-box w-3/12 h-full" style="background-color: rgba(209,208,208,0.2); border-radius: 16px;margin-left: 10px">
          <v-chart ref="dynamicRef" v-if="aggregate"/>
          <el-empty v-else description="暂无数据" />
<!--          <div class="w-full h-1/2 flex items-center justify-between">-->
<!--            <div class="w-full bg-gray-100 rounded-2xl ml-4 p-5 card-box">-->
<!--              <span class="font-normal text-sl">本月入库总计</span>-->
<!--              <div class="font-bold  dynamic-text">{{ currentMonthQty }}</div>-->
<!--            </div>-->
<!--          </div>-->
<!--          <div class="w-full h-1/2  flex items-center justify-between">-->
<!--            <div class="w-full bg-gray-100 rounded-2xl ml-4 p-5 card-box2">-->
<!--              <div class="text-box">-->
<!--              <span class="font-normal text-sl">上月入库总计</span>-->
<!--              <div class="font-bold dynamic-text ">{{ lastMonthQty }}</div>-->
<!--              </div>-->
<!--            </div>-->
<!--          </div>-->
        </div>
      </div>
    </div>

  </div>

</template>
<script setup>
import '@/assets/font/iconfont.css'
import materialStorageList from './materialStorageList.vue'
import { onMounted, reactive, ref } from 'vue'
import { getInstockMaterialRank, getInstockSum } from '@/api/warehouseEntryApi'
import * as echarts from 'echarts';
import moment from 'moment/moment'

const from = reactive({
  time: [],
})

const currentRef = ref()
const currentMonthQty = ref()
const lastMonthQty = ref()
const chartNameList = ref([])
const chartNumList = ref([])
const list = ref([])
const dynamicRef = ref()
const taskDate = ref([])
const aggregate= ref()
const renderOption = () => {
  const offsetX = 24;  //bar宽
  const offsetY = 6;   //倾斜角度
// 绘制左侧面
  const CubeLeft = echarts.graphic.extendShape({
    shape: {
      x: 0,
      y: 0,
    },
    buildPath: function (ctx, shape) {
      const xAxisPoint = shape.xAxisPoint;
      const c0 = [shape.x, shape.y];
      const c1 = [shape.x - offsetX, shape.y - offsetY];
      const c2 = [xAxisPoint[0] - offsetX, xAxisPoint[1] - offsetY];
      const c3 = [xAxisPoint[0], xAxisPoint[1]];
      ctx.moveTo(c0[0], c0[1]).lineTo(c1[0], c1[1]).lineTo(c2[0], c2[1]).lineTo(c3[0], c3[1]).closePath();
    },
  });
// 绘制右侧面
  const CubeRight = echarts.graphic.extendShape({
    shape: {
      x: 0,
      y: 0,
    },
    buildPath: function (ctx, shape) {
      const xAxisPoint = shape.xAxisPoint;
      const c1 = [shape.x, shape.y];
      const c2 = [xAxisPoint[0], xAxisPoint[1]];
      const c3 = [xAxisPoint[0] + offsetX, xAxisPoint[1] - offsetY];
      const c4 = [shape.x + offsetX, shape.y - offsetY];
      ctx.moveTo(c1[0], c1[1]).lineTo(c2[0], c2[1]).lineTo(c3[0], c3[1]).lineTo(c4[0], c4[1]).closePath();
    },
  });
// 绘制顶面
  const CubeTop = echarts.graphic.extendShape({
    shape: {
      x: 0,
      y: 0,
    },
    buildPath: function (ctx, shape) {
      const c1 = [shape.x, shape.y];
      const c2 = [shape.x + offsetX, shape.y - offsetY]; //右点
      // const c3 = [shape.x, shape.y - offsetX];
      const c3 = [shape.x, shape.y - offsetY * 2];
      const c4 = [shape.x - offsetX, shape.y - offsetY];
      ctx.moveTo(c1[0], c1[1]).lineTo(c2[0], c2[1]).lineTo(c3[0], c3[1]).lineTo(c4[0], c4[1]).closePath();
    },
  });
// 注册三个面图形
  echarts.graphic.registerShape('CubeLeft', CubeLeft);
  echarts.graphic.registerShape('CubeRight', CubeRight);
  echarts.graphic.registerShape('CubeTop', CubeTop);

  let colorArr = [["#12D5AF"], ["#0BC19D", "rgba(13,8,16,0)"], ["#68EFD4", "rgba(14,185,151,0)"]]

  return  {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
      backgroundColor: 'rgba(255, 255, 255, 0.9)', // 背景颜色更不透明
      borderColor: '#2B7BD6', // 边框颜色
      borderWidth: 2, // 边框宽度增加
      padding: 15, // 增加内边距
      textStyle: {
        fontSize: 18, // 增加字体大小
        color: '#333', // 字体颜色
      },
      formatter: function (params) {
        const item = params[1]; // 选择第二个参数
        return `
          <div style="text-align: left; font-size: 18px;">
            <strong style="color: #2B7BD6;">${item.name}</strong><br/>
            <span style="color: #333;"><span style="color: #22c4ff;">${item.data.value} ${item.data.unit}</span></span> <!-- 增加单位 -->
          </div>
        `;
      },
    },
    grid: {
      left: '3%',
      right: '3%',
      top: '20%',
      bottom: '10%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: chartNameList.value || [],
      axisLine: {
        show: true,
        lineStyle: {
          width: 2,
          color: '#2B7BD6',
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        fontSize: 14,
        interval: 0,
        color: '#000000',
        fontFamily: 'siyuan',
        margin: 5,
        fontWeight: 'bold',
        interval: 0,  // 显示所有标签
        // rotate: 13,   // 设置倾斜角度
      },
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: true,
        lineStyle: {
          width: 2,
          color: '#2B7BD6',
        },
      },
      splitLine: {
        show: true,
        lineStyle: {
          // width: 1,
          type:'dashed',
          color: '#153D7D',
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        show: true,
        color: '#000000',
        fontSize: 16,
        fontWeight: 'bold', // 设置文本加粗
      },
      // boundaryGap: ['20%', '20%'],
    },
    series: [
      {
        type: 'custom',
        renderItem: (params, api) => {
          const location = api.coord([api.value(0), api.value(1)]);
          return {
            type: 'group',
            children: [
              {
                type: 'CubeLeft',
                shape: {
                  api,
                  xValue: api.value(0),
                  yValue: api.value(1),
                  x: location[0],
                  y: location[1],
                  xAxisPoint: api.coord([api.value(0), 0]),
                },
                style: {
                  fill: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {
                      offset: 0,
                      color: colorArr[1][0],
                    },
                    {
                      offset: 1,
                      color: colorArr[1][1],
                    },
                  ]),
                },
              },
              {
                type: 'CubeRight',
                shape: {
                  api,
                  xValue: api.value(0),
                  yValue: api.value(1),
                  x: location[0],
                  y: location[1],
                  xAxisPoint: api.coord([api.value(0), 0]),
                },
                style: {
                  fill: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {
                      offset: 0,
                      color: colorArr[2][0],
                    },
                    {
                      offset: 1,
                      color: colorArr[2][1],
                    },
                  ]),
                },
              },
              {
                type: 'CubeTop',
                shape: {
                  api,
                  xValue: api.value(0),
                  yValue: api.value(1),
                  x: location[0],
                  y: location[1],
                  xAxisPoint: api.coord([api.value(0), 0]),
                },
                style: {
                  fill: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {
                      offset: 0,
                      color: colorArr[0][0],
                    },
                    {
                      offset: 1,
                      color: colorArr[0][0],
                    },
                  ]),
                },
              },
            ],
          };
        },
        data: chartNumList.value || [],
      },
      {
        type: 'bar',
        label: {
          normal: {
            show: true,
            position: 'top',
            formatter: (e) => {
              // return e.value + '次';
              return e.value;
            },
            fontSize: 16,
            // color: "#2B7BD6",
            color: '#000000',
            fontFamily: 'siyuan',
            fontWeight: 'bold',
            offset: [0, -15],
            // rotate: 13,  // 设置倾斜角度
          },
        },
        itemStyle: {
          color: 'transparent',
        },
        tooltip: {},
        data: chartNumList.value || [],
      },
    ],
  }

}

const dynamicRenderOption =(data,total) =>{
  return {
    tooltip: {
      trigger: "item"
    },
    legend: {
      orient: 'horizontal', // 水平排列
      bottom: '5%', // 设置位置在底部
      // left: 'center', // 设置位置居中
      data: [
        { name: '本月原材料入库', icon: 'rect' },
        { name: '上月原材料入库', icon: 'rect' },
        { name: '本月五金入库', icon: 'rect' }
      ],
      itemGap: 10, // 设置项之间的间隔
      textStyle: {
        color: '#333', // 设置图例文字颜色
        fontSize: '14',
      },
      itemWidth: 30, // 图例项的宽度
      itemHeight: 15, // 图例项的高度
    },
    series: [
      {
        type: "pie",
        radius: ["20%", "45%"],
        center: ["50%", "50%"], // 向上移动，Y 坐标改为 40%
        data: data,
        hoverAnimation: false,
        itemStyle: {
          normal: {
            borderColor: "#fff",
            borderWidth: 2
          }
        },
        labelLine: {
          normal: {
            length: 40,
            length2:30,
            lineStyle: {
              // color: '#e6e6e6'
            }
          }
        },
        label: {
          normal: {
            formatter: function(params, ticket, callback) {
              let total = 0; //总数量
              let percent = 0; //占比
              data.forEach(function(value, index, array) {
                total += value.value;
              });
              let formatNumber = function(num) {
                let reg = /(?=(\B)(\d{3})+$)/g;
                return num.toString().replace(reg, ',');
              }
              percent = ((params.value / total) * 100).toFixed(1);
              return (
                '{name|' + params.name + '}\n{value|' +
                formatNumber(params.value)  + '}'
              )
            },
            padding: [10, -40, 10, -80], // 调整内边距
            rich: {
              icon: {
                fontSize: 16,
                color: 'inherit',
              },
              name: {
                fontSize: 14,
                padding: [0, 0, 0, 10],
                color: '#000'
              },
              value: {
                fontSize: 16,
                fontWeight: 'bolder',
                padding: [10, 0, 0, 20],
                color: 'inherit'
                // color: '#333333'
              }
            }
          }
        }

      }
    ]
  }
}

const getDefaultDateRange = () => {
  const start = moment().startOf('month'); // 本月一号
  const end = moment(); // 今天
  // return [start.toDate(), end.toDate()]; // 转换为 Date 对象
  from.time= [start.toDate(), end.toDate()]

}

const getNumObj = async () => {
  try {
    const params = {
      startTime: from?.time?.[0] ? moment(from.time[0]).format('YYYY-MM-DD') : '',
      endTime:  from?.time?.[1] ? moment(from.time[1]).format('YYYY-MM-DD') : '',
    }
    const { data } = await getInstockMaterialRank(params)
    list.value = data
    chartNameList.value = data?.slice(0, 10).map(item => item.materialCode);
    chartNumList.value = data.slice(0, 10).map(item => ({
      value: item.qty,
      unit: item.unit // 添加单位
    }));

  } catch (e) {
    console.log(e)
  }

}

const getInstockObj = async () => {
  try {
    const params = {
      startTime: from?.time?.[0] ? moment(from.time[0]).format('YYYY-MM-DD') : '',
      endTime:  from?.time?.[1] ? moment(from.time[1]).format('YYYY-MM-DD') : '',
    }
    const { data } = await getInstockSum(params)
    // currentMonthQty.value = data.currentMonthQty
    // currentMonthHardwareQty.value = data.currentMonthHardwareQty
    // lastMonthQty.value = data.lastMonthQty
    aggregate.value = data.currentMonthQty+data.currentMonthHardwareQty+data.lastMonthQty
    taskDate.value = [
      {value: data.currentMonthQty, name: '本月原材料入库', itemStyle: { color: '#409eff' }},
      {value: data.lastMonthQty, name: '上月原材料入库', itemStyle: { color: '#8f51da' }},
      {value: data.currentMonthHardwareQty, name: '本月五金入库', itemStyle: { color: '#ffc446' }}
    ]

  } catch (e) {
    console.log(e)
  }

}
const getSerch = async () =>{
  await getNumObj()
  if(currentRef.value){
    currentRef.value.setOption(renderOption())
  }
  getInstockObj()
  if(dynamicRef.value){
    dynamicRef.value.setOption(dynamicRenderOption(taskDate.value,aggregate.value))
  }
}

onMounted(async () => {
  await getDefaultDateRange()
  await getNumObj()
  await getInstockObj()
  if(currentRef.value){
    currentRef.value.setOption(renderOption())
  }
  if(dynamicRef.value){
    dynamicRef.value.setOption(dynamicRenderOption(taskDate.value,aggregate.value))
  }


})
</script>


<style scoped lang="scss">
:deep(.el-form) {
  height: 18px;
  display: flex;
  justify-content: center;
}
@keyframes gradient {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

@keyframes blink {
  0%, 100% {
    opacity: 1; /* 完全可见 */
  }
  50% {
    opacity: 0.5; /* 半透明 */
  }
}

.dynamic-text {
  font-size: 38px;
  font-weight: bold;
  background: linear-gradient(270deg, #120101, #01350b, #162c02);
  background-size: 300% 300%;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  animation: gradient 3s ease infinite, blink 1s infinite; /* 应用渐变和闪烁动画 */
}
.card-box,.card-box2{
  background-image: url("@/assets/images/bgcard.png");
  background-size: cover; /* 使背景图像覆盖整个元素 */
  background-position: center; /* 使背景图像居中 */
  background-repeat: no-repeat; /* 不重复背景图像 */
  padding-left: 30px;
  padding-top: 30px;
}
.card-box2 {
  transform: scaleX(-1);
  transform: scaleY(-1);
  padding-top: 26px;
}
.text-box{
  transform: scaleX(-1);
  transform: scaleY(-1);
  padding-top: 15px;
}
</style>
